package com.ruoyi.asset.service.impl;

import java.util.Date;
import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;

import com.ruoyi.asset.domain.AssetInfo;
import com.ruoyi.base.domain.BaseOrganization;
import com.ruoyi.base.domain.BaseWarehouse;
import com.ruoyi.base.service.IBaseWarehouseService;
import com.ruoyi.common.core.domain.entity.SysDept;
import com.ruoyi.common.core.domain.entity.SysUser;
import com.ruoyi.common.exception.ServiceException;
import com.ruoyi.common.utils.StringUtils;
import com.ruoyi.common.utils.bean.BeanValidators;
import com.ruoyi.system.service.ISysDeptService;
import com.ruoyi.system.service.ISysUserService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import com.ruoyi.asset.mapper.AssetStockDetailMapper;
import com.ruoyi.asset.domain.AssetStockDetail;
import com.ruoyi.asset.service.IAssetStockDetailService;

import javax.validation.Validator;

/**
 * 盘点记录Service业务层处理
 * 
 * @author asset
 * @date 2024-12-25
 */
@Service
@Slf4j
public class AssetStockDetailServiceImpl implements IAssetStockDetailService 
{
    @Autowired
    private AssetStockDetailMapper assetStockDetailMapper;

    @Autowired
    protected ISysDeptService deptService;

    @Autowired
    protected ISysUserService userService;

    @Autowired
    protected IBaseWarehouseService baseWarehouseService;

    @Autowired
    protected Validator validator;

    /**
     * 查询设备最新的盘点记录
     *
     * @param assetId 设备主键
     * @return 盘点记录
     */
    @Override
    public AssetStockDetail selectAssetStockDetailByAssetId(Long assetId){
        return assetStockDetailMapper.selectAssetStockDetailByAssetId(assetId);
    }

    /**
     * 查询盘点记录
     * 
     * @param id 盘点记录主键
     * @return 盘点记录
     */
    @Override
    public AssetStockDetail selectAssetStockDetailById(Long id)
    {
        return assetStockDetailMapper.selectAssetStockDetailById(id);
    }

    /**
     * 查询盘点记录列表
     * 
     * @param assetStockDetail 盘点记录
     * @return 盘点记录
     */
    @Override
    public List<AssetStockDetail> selectAssetStockDetailList(AssetStockDetail assetStockDetail)
    {
        return assetStockDetailMapper.selectAssetStockDetailList(assetStockDetail);
    }

    /**
     * 新增盘点记录
     * 
     * @param assetStockDetail 盘点记录
     * @return 结果
     */
    @Override
    public int insertAssetStockDetail(AssetStockDetail assetStockDetail)
    {
        return assetStockDetailMapper.insertAssetStockDetail(assetStockDetail);
    }

    /**
     * 修改盘点记录
     * 
     * @param assetStockDetail 盘点记录
     * @return 结果
     */
    @Override
    public int updateAssetStockDetail(AssetStockDetail assetStockDetail)
    {
        BeanValidators.validateWithException(validator, assetStockDetail);
        if(assetStockDetail.getPriceOld() != null
                && assetStockDetail.getPriceNew().compareTo(assetStockDetail.getPriceOld()) > 0){
            throw new ServiceException("新价值不能大于原价值");
        }
        if(assetStockDetail.getHouseId() != null){
            BaseWarehouse baseWarehouse = baseWarehouseService.selectBaseWarehouseById(assetStockDetail.getHouseId());
            if(baseWarehouse != null){
                assetStockDetail.setHouseName(baseWarehouse.getName());
            }else{
                assetStockDetail.setHouseId(null);
            }
        }
        if(assetStockDetail.getDeptId() != null){
            SysDept sysDept = deptService.selectDeptById(assetStockDetail.getDeptId());
            if(sysDept != null){
                assetStockDetail.setDeptName(sysDept.getDeptName());
            }else{
                sysDept.setDeptId(null);
            }
        }
        if(assetStockDetail.getUserId() != null){
            SysUser sysUser = userService.selectUserById(assetStockDetail.getUserId());
            if(sysUser != null){
                assetStockDetail.setUserName(sysUser.getNickName());
            }else{
                assetStockDetail.setUserId(null);
            }
        }
        if(assetStockDetail.getUserId() != null
                && assetStockDetail.getIsUse().equalsIgnoreCase("N")){
            throw new ServiceException("有使用人的资产不能为闲置状态");
        }
        if(assetStockDetail.getUserId() == null
                && assetStockDetail.getIsUse().equalsIgnoreCase("Y")){
            throw new ServiceException("有使用人不能为空");
        }
        assetStockDetail.setTaskTime(new Date());
        return assetStockDetailMapper.updateAssetStockDetail(assetStockDetail);
    }

    /**
     * 批量删除盘点记录
     * 
     * @param ids 需要删除的盘点记录主键
     * @return 结果
     */
    @Override
    public int deleteAssetStockDetailByIds(Long[] ids)
    {
        return assetStockDetailMapper.deleteAssetStockDetailByIds(ids);
    }

    /**
     * 删除盘点记录信息
     * 
     * @param id 盘点记录主键
     * @return 结果
     */
    @Override
    public int deleteAssetStockDetailById(Long id)
    {
        return assetStockDetailMapper.deleteAssetStockDetailById(id);
    }
    /**
     * 导入数据
     *
     * @param dataList 数据列表
     * @param isUpdateSupport 是否更新支持，如果已存在，则进行更新数据
     * @return 结果
     */
    public String importData(List<AssetStockDetail> dataList, Boolean isUpdateSupport){
        if (StringUtils.isNull(dataList) || dataList.size() == 0)
        {
            throw new ServiceException("导入数据不能为空！");
        }
        int successNum = 0;
        int failureNum = 0;
        StringBuilder successMsg = new StringBuilder();
        StringBuilder failureMsg = new StringBuilder();
        Map<String, SysDept> deptMap = deptService.selectDeptList(new SysDept()).stream().collect(Collectors.toMap(SysDept::getDeptName, SysDept->SysDept));
        Map<String, SysUser> userMap = userService.selectUserList(new SysUser()).stream().collect(Collectors.toMap(SysUser::getNickName, SysUser->SysUser));
        Map<String, BaseWarehouse> houseMap = baseWarehouseService.selectBaseWarehouseList(new BaseWarehouse()).stream().collect(Collectors.toMap(BaseWarehouse::getName, BaseWarehouse->BaseWarehouse));
        for (AssetStockDetail row : dataList)
        {
            try
            {
                // 验证是否存在这个用户
                AssetStockDetail old = assetStockDetailMapper.selectAssetStockDetailById(row.getId());
                if (StringUtils.isNull(old))
                {
                    failureNum++;
                    failureMsg.append("<br/>" + successNum + "、资产盘点任务 " + row.getAssetNum() + "不存在");
                }
                else
                {
                    BeanValidators.validateWithException(validator, row);
                    if(row.getPriceOld() != null
                            && row.getPriceNew().compareTo(row.getPriceOld()) > 0){
                        throw new ServiceException(row.getAssetNum() + " 新价值不能大于原价值");
                    }
                    if(row.getHouseName() != null){
                        BaseWarehouse baseWarehouse = houseMap.get(row.getHouseName());
                        if(baseWarehouse != null){
                            row.setHouseId(baseWarehouse.getId());
                        }else{
                            throw new ServiceException(row.getAssetNum() + " 仓库不存在");
                        }
                    }
                    if(row.getDeptName() != null){
                        SysDept sysDept = deptMap.get(row.getDeptName());
                        if(sysDept != null){
                            row.setDeptId(sysDept.getDeptId());
                        }else{
                            throw new ServiceException(row.getAssetNum() + " 部门不存在");
                        }
                    }
                    if(row.getUserName() != null){
                        SysUser sysUser = userMap.get(row.getUserName());
                        if(sysUser != null){
                            row.setUserId(sysUser.getUserId());
                        }else{
                            throw new ServiceException(row.getAssetNum() + " 用户不存在");
                        }
                    }
                    if(row.getUserId() != null
                            && row.getIsUse().equalsIgnoreCase("N")){
                        throw new ServiceException("有使用人的资产不能为闲置状态");
                    }
                    row.setTaskTime(new Date());

                    assetStockDetailMapper.updateAssetStockDetail(row);
                    successNum++;
                    successMsg.append("<br/>" + successNum + "、资产 " + row.getAssetNum() + " 盘点成功");
                }
            }
            catch (Exception e)
            {
                failureNum++;
                String msg = "<br/>" + failureNum + "、资产 " + row.getAssetNum() + " 盘点失败：";
                failureMsg.append(msg + e.getMessage());
                log.error(msg, e);
            }
        }
        if (failureNum > 0)
        {
            failureMsg.insert(0, "很抱歉，导入失败！共 " + failureNum + " 条数据格式不正确，错误如下：");
            throw new ServiceException(failureMsg.toString());
        }
        else
        {
            successMsg.insert(0, "恭喜您，数据已全部导入成功！共 " + successNum + " 条，数据如下：");
        }
        return successMsg.toString();
    }
}
